package cn.iocoder.yudao.module.member.vip.controller.app;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.pojo.vo.UserSimpleVO;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.api.cms.benefit.BenefitApi;
import cn.iocoder.yudao.module.api.cms.benefit.dto.BenefitRespDTO;
import cn.iocoder.yudao.module.api.infrastructure.config.ConfigApiV2;
import cn.iocoder.yudao.module.api.infrastructure.config.dto.MemberConfigRespDTO;
import cn.iocoder.yudao.module.api.infrastructure.social.SocialUserApi;
import cn.iocoder.yudao.module.api.infrastructure.social.dto.SocialUserRespDTO;
import cn.iocoder.yudao.module.api.infrastructure.social.enums.SocialTypeEnum;
import cn.iocoder.yudao.module.api.member.vip.vo.VipUserVO;
import cn.iocoder.yudao.module.api.shop.info.ShopInfoApi;
import cn.iocoder.yudao.module.member.user.dal.dataobject.MemberUserDO;
import cn.iocoder.yudao.module.member.user.service.MemberUserService;
import cn.iocoder.yudao.module.member.vip.dal.dataobject.VipUserDO;
import cn.iocoder.yudao.module.member.vip.service.AppVipUserService;
import cn.iocoder.yudao.module.member.vip.service.VipCardService;
import cn.iocoder.yudao.module.member.vip.vo.AppVipDetailVO;
import cn.iocoder.yudao.module.member.vip.vo.VipCardVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.api.infrastructure.ConfigConstants.CONFIG_MEMBER;
import static cn.iocoder.yudao.module.api.member.DictTypeConstants.MEMBER_VIP_BENEFIT;
import static cn.iocoder.yudao.module.api.member.DictTypeConstants.MERCHANT_VIP_BENEFIT;

@Tag(name = "用户 APP - 会员信息")
@RestController
@RequestMapping("/member/vip")
@Validated
public class AppVipUserController {

    @Resource
    private AppVipUserService appVipUserService;
    @Resource
    private VipCardService vipCardService;
    @Resource
    private MemberUserService memberUserService;

    @Resource
    private ConfigApiV2 configApiV2;
    @Resource
    private BenefitApi benefitApi;
    @Resource
    private ShopInfoApi shopInfoApi;
    @Resource
    private SocialUserApi socialUserApi;

    @GetMapping("/my")
    @Operation(summary = "获得我的会员详情", description = "返回会员卡购买信息，还不是会员的话可进行展示")
    @Parameter(name = "profile", description = "是否含当前用户信息", example = "false")
    @Parameter(name = "cards", description = "可购买的会员卡数", example = "1")
    @PermitAll // 扫商家码收款页面有调用，允许匿名访问
    public CommonResult<AppVipDetailVO> getMyVip(@RequestParam(value = "profile", required = false, defaultValue = "false") Boolean profile, @RequestParam(value = "cards", required = false, defaultValue = "1") Integer cards) {
        AppVipDetailVO respVO = new AppVipDetailVO();
        Long userId = getLoginUserId();
        if (userId == null || userId <= 0) {
            List<VipCardVO> list = vipCardService.getList(false, cards);
            respVO.setCards(list);
            respVO.setProfile(null);
            respVO.setOpenid("");
        } else {
            VipUserDO vip = appVipUserService.getOrCreate(userId);
            respVO = BeanUtils.toBean(vip, AppVipDetailVO.class);
            boolean isMerchant = shopInfoApi.isOwnerByMemberUserId(userId);
            List<VipCardVO> list = vipCardService.getList(isMerchant, cards);
            respVO.setCards(list);
            if (Boolean.TRUE.equals(profile)) {
                MemberUserDO user = memberUserService.getUser(vip.getUserId());
                respVO.setProfile(BeanUtils.toBean(user, UserSimpleVO.class));
            } else {
                respVO.setProfile(null);
            }
            SocialUserRespDTO socialUserRespDTO = socialUserApi.getSocialUserByUserId(UserTypeEnum.MEMBER.getValue(), userId, SocialTypeEnum.WECHAT_MINI_PROGRAM.getType());
            if (socialUserRespDTO != null) {
                respVO.setOpenid(socialUserRespDTO.getOpenid());
            } else {
                respVO.setOpenid("");
            }
        }
        if (CollUtil.isNotEmpty(respVO.getCards())) {
            int deductUnitPrice = configApiV2.getConfig(CONFIG_MEMBER, MemberConfigRespDTO.class).getPointTradeDeductUnitPrice();
            for (VipCardVO item : respVO.getCards()) {
                item.setDeductPrice(deductUnitPrice * item.getGivePoint());
            }
        }
        return success(respVO);
    }

    @GetMapping("/benefit")
    @Operation(summary = "获得会员权益列表")
    public CommonResult<List<BenefitRespDTO>> getBenefit() {
        boolean isMerchant = shopInfoApi.isOwnerByMemberUserId(getLoginUserId());
        if (isMerchant) {
            return success(benefitApi.getBenefitList(MERCHANT_VIP_BENEFIT));
        }
        return success(benefitApi.getBenefitList(MEMBER_VIP_BENEFIT));
    }

    @GetMapping("/page-by-shop")
    @Operation(summary = "获得商家绑定的会员列表")
    @Parameter(name = "pageNo", description = "页码", required = true, example = "1")
    @Parameter(name = "pageSize", description = "每页数据条数", required = true, example = "10")
    @Parameter(name = "valid", description = "是否有效", example = "false")
    @PreAuthorize("@mm.isMerchant()")
    public CommonResult<PageResult<VipUserVO>> getPage(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, @RequestParam(value = "valid", required = false) Boolean valid) {
        Long userId = getLoginUserId();
        Long shopId = shopInfoApi.getShopIdByMemberUserId(userId);
        return success(appVipUserService.getPage(pageNo, pageSize, valid, shopId));
    }

}